package com.mashibing.juc.c_020_Interview;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * notify()方法不释放锁
 * @author: Yuanzt
 * @Date: 2021/3/29
 */
public class T03_NotifyHoldingLock {

    //添加volatile，使Thread-2能够得到通知
    volatile List list = new ArrayList();

    public void add(Object o) {
        list.add(o);
    }

    public int size(){
        return list.size();
    }

    public static void main(String[] args) {
        T03_NotifyHoldingLock t = new T03_NotifyHoldingLock();
        final Object lock = new Object();
        new Thread(()->{
            synchronized (lock){
                System.out.println("thread-2 start");
                if (t.size() != 5){
                    try {
                        lock.wait();//无法拿到锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("thread-2 end");
            }
        },"thread-2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(()->{
            System.out.println("thread-1 start");
            synchronized (lock){
                for (int i = 0; i < 10; i++) {
                    t.add(new Object());
                    System.out.println("add " + i);
                    if (t.size() == 5)
                        lock.notify();//不释放锁
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        },"thread-1").start();
    }
}
